<template>
  <div class="left">
    <div class="leftTitle">
      <span class="leftTitleText" :class="{ activeText: selectedIndex === 0 }" @click="selectTab(0)">TODAY</span>
      <span class="leftTitleText" :class="{ activeText: selectedIndex === 1 }" @click="selectTab(1)">DAY1</span>
      <span class="leftTitleText" :class="{ activeText: selectedIndex === 2 }" @click="selectTab(2)">DAY2</span>
      <span class="leftTitleText" :class="{ activeText: selectedIndex === 3 }" @click="selectTab(3)">DAY3</span>
      <span class="leftTitleText" :class="{ activeText: selectedIndex === 4 }" @click="selectTab(4)">DAY4</span>
      <span class="leftTitleText" :class="{ activeText: selectedIndex === 5 }" @click="selectTab(5)">DAY5</span>
    </div>
    <div class="leftSearch">
      <div>
        <a-input-search v-model:value="searckFrom" placeholder="手机号/最近消息/联系人"
          style="width: 180px;height: 32px;margin-left: 5px;" @search="onSearch" />
      </div>
      <div class="leftDropdown">
        <a-dropdown placement="right" :trigger="['click']" :visible="dropdownVisible" @visibleChange="handleVisibleChange">
          <a class="ant-dropdown-link" @click.prevent
            style="color: black;font-size:14px;white-space: nowrap;margin-right: 5px;">
            全部筛选
            <DownOutlined />
          </a>
          <template #overlay>
            <div class="filter-menu">
              <div class="filter-section">
                <div class="filter-header">
                  <span>客户回复次数分组</span>
                  <a-button type="link" size="small" @click.stop="clearFilter">清空</a-button>
                </div>
                <div class="filter-buttons">
                  <a-button :type="selectedFilters.reply === 'reply1' ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.reply === 'reply1' ? 'selected-button' : '']" 
                           @click.stop="applyFilter('reply', 'reply1')">一回会话</a-button>
                  <a-button :type="selectedFilters.reply === 'reply2' ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.reply === 'reply2' ? 'selected-button' : '']" 
                           @click.stop="applyFilter('reply', 'reply2')">二回会话</a-button>
                  <a-button :type="selectedFilters.reply === 'reply3' ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.reply === 'reply3' ? 'selected-button' : '']" 
                           @click.stop="applyFilter('reply', 'reply3')">三回会话</a-button>
                  <a-button :type="selectedFilters.reply === 'reply4' ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.reply === 'reply4' ? 'selected-button' : '']" 
                           @click.stop="applyFilter('reply', 'reply4')">四回会话</a-button>
                  <a-button :type="selectedFilters.reply === 'reply5' ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.reply === 'reply5' ? 'selected-button' : '']" 
                           @click.stop="applyFilter('reply', 'reply5')">五回会话</a-button>
                  <a-button :type="selectedFilters.reply === 'reply5plus' ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.reply === 'reply5plus' ? 'selected-button' : '']" 
                           @click.stop="applyFilter('reply', 'reply5plus')">五回以上</a-button>
                </div>
              </div>
              
              <div class="filter-section">
                <div class="filter-header">
                  <span>待回复分组</span>
                </div>
                <div class="filter-buttons">
                  <a-button :type="selectedFilters.waiting ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.waiting ? 'selected-button' : '']" 
                           @click.stop="applyFilter('waiting', true)">待回复</a-button>
                </div>
              </div>
              
              <div class="filter-section">
                <div class="filter-header">
                  <span>未读分组</span>
                </div>
                <div class="filter-buttons">
                  <a-button :type="selectedFilters.unread ? 'primary' : 'default'" 
                           :class="['filter-button', selectedFilters.unread ? 'selected-button' : '']" 
                           @click.stop="applyFilter('unread', true)">未读会话</a-button>
                </div>
              </div>
            </div>
          </template>
        </a-dropdown>
      </div>
    </div>
    <div class="leftData">
      <span>会话总数:{{ messageList.length }} 总未读数:{{ totalUnread }} 异常:0</span>
      <span class="leftDataText" @click="refreshList">
        <RedoOutlined :class="{ 'refreshing': isRefreshing }" />
      </span>
    </div>

    <div class="overLeft" style="overflow-y: auto;">
      <div class="leftList" v-for="(item, index) in messageList" :key="index" @click="clickList(item)">
        <div class="leftListBox">
          <div style="width: 40px;height:40px;">
            <img src="../assets/avator.png" style="width: 40px;height:40px;margin-top:8px">
          </div>
          <div class="leftListBoxRight">
            <div class="leftListBoxRightTop">
              <span class="contact-name">{{ item.contactId }}{{ item.contactPushName ? ` (${item.contactPushName})` : '' }}</span>
              <span>{{ item.ts }}</span>
            </div>
            <div class="leftListBoxRightCenter">坐席：{{ item.tenantId }} </div>
              <div class="leftListBoxRightCenter message-content">
                <span class="message-text">
                  <template v-if="item.payload.text">{{ item.payload.text }}</template>
                  <template v-else>
                    <template v-if="item.msgType === 1">[图文消息]</template>
                    <template v-else-if="item.msgType === 2">[音频文件]</template>
                    <template v-else-if="item.msgType === 3">[视频文件]</template>
                    <template v-else-if="item.msgType === 11">[语音通话]</template>
                    <template v-else-if="item.msgType === 12">[视频通话]</template>
                    <template v-else>[其他类型消息]</template>
                  </template>
                </span>
                <a-badge v-if="!item.isRead" :count="item.unRead" :overflowCount="99" />
              </div>

            <div class="leftListBoxRightBottom">
              <div>
                <a-tag color="orange" v-if="item.group">群聊</a-tag>
                <a-tag color="green" v-else="item.group">单聊</a-tag>
                <a-tag color="cyan">被动聊天</a-tag>
                <a-tag color="success">坐席在线</a-tag>
              </div>
              <div>
                <img src="../assets/go.png" alt="">
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue';
import { DownOutlined, RedoOutlined } from '@ant-design/icons-vue';
import { useChatStore } from '../stores/chat';
import requests from '../utils/requests';
import moment from 'moment';

const chatStore = useChatStore();
const searckFrom = ref('');
const count = ref(100);
const selectedIndex = ref(0);

// 筛选后的消息列表
const messageList = computed(() => {
  const allMessages = chatStore.messageList;
  let filteredMessages = allMessages;
  
  // 首先按日期筛选
  if (selectedIndex.value === 0) {
    // TODAY - 今天的消息
    filteredMessages = allMessages.filter(item => {
      // 使用原始时间戳进行比较
      const originalDate = item._originalTs || item.ts;
      const msgDate = moment(originalDate, "YYYY/MM/DD HH:mm:ss");
      return msgDate.isValid() && msgDate.isSame(moment(), 'day');
    });
  } else if (selectedIndex.value >= 1 && selectedIndex.value <= 5) {
    // DAY1-DAY5 - 过去1-5天的消息
    const daysAgo = selectedIndex.value;
    filteredMessages = allMessages.filter(item => {
      // 使用原始时间戳进行比较
      const originalDate = item._originalTs || item.ts;
      const msgDate = moment(originalDate, "YYYY/MM/DD HH:mm:ss");
      return msgDate.isValid() && msgDate.isSame(moment().subtract(daysAgo, 'days'), 'day');
    });
  }
  
  // 然后应用筛选条件
  if (selectedFilters.value.reply) {
    // 回复次数筛选
    if (selectedFilters.value.reply === 'reply5plus') {
      // 五回以上，reply > 5
      filteredMessages = filteredMessages.filter(item => item.reply > 5);
    } else {
      // 一到五回会话，精确匹配reply值
      const replyCount = parseInt(selectedFilters.value.reply.replace('reply', ''));
      filteredMessages = filteredMessages.filter(item => item.reply === replyCount);
    }
  }
  
  // 待回复筛选：reply >= 1 且 unRead > 0
  if (selectedFilters.value.waiting) {
    filteredMessages = filteredMessages.filter(item => 
      (item.reply >= 1) && (item.unRead > 0)
    );
  }
  
  // 未读筛选：unRead > 0
  if (selectedFilters.value.unread) {
    filteredMessages = filteredMessages.filter(item => item.unRead > 0);
  }
  
  return filteredMessages;
});

// 选择标签页
const selectTab = (index) => {
  selectedIndex.value = index;
};

// 点击联系人列表项
const clickList = async (item) => {
  await chatStore.fetchChatMessages(item);
  chatStore.scrollToBottom();
  
  // 调用未读确认接口，但不更新未读状态
  // try {
  //   await requests.post('/api/externalContacts/unReadCheck', {
  //     contactId: item.contactId,
  //     uid: item.uid
  //   });
    
  //   // 不再在这里更新消息列表中的已读状态
  //   // 只保存当前选中的联系人信息，以便后续发送消息时使用
  // } catch (error) {
  //   console.error('未读确认失败:', error);
  // }
};

// 搜索功能
const onSearch = (value) => {
  if (!value) {
    return;
  }
  // 在现有的消息列表中进行本地搜索
  const searchValue = value.toLowerCase();
  return messageList.value.filter(item => {
    return (
      item.contactId?.toLowerCase().includes(searchValue) ||
      item.contactPushName?.toLowerCase().includes(searchValue) ||
      item.payload?.text?.toLowerCase().includes(searchValue)
    );
  });
};

// 计算总未读数和会话总数
const totalUnread = computed(() => {
  return messageList.value.reduce((sum, item) => sum + (item.unRead || 0), 0);
});

const totalChats = computed(() => {
  return messageList.value.reduce((sum, item) => sum + (item.reply || 0), 0);
});

// 在 script setup 部分添加加载状态
const isRefreshing = ref(false);

// 修改刷新方法
const refreshList = async () => {
  if (isRefreshing.value) return; // 防止重复点击
  
  try {
    isRefreshing.value = true;
    await chatStore.fetchChatsList();
  } catch (error) {
    console.error('刷新列表失败:', error);
  } finally {
    isRefreshing.value = false;
  }
};

// 添加筛选状态变量
const selectedFilters = ref({
  reply: null,  // 回复次数筛选
  waiting: false, // 待回复筛选
  unread: false   // 未读筛选
});

// 清空筛选条件
const clearFilter = () => {
  selectedFilters.value = {
    reply: null,
    waiting: false,
    unread: false
  };
  console.log('已清空筛选条件');
};

// 添加下拉菜单控制
const dropdownVisible = ref(false);

// 处理下拉菜单可见性变化
const handleVisibleChange = (visible) => {
  dropdownVisible.value = visible;
};

// 应用筛选条件
const applyFilter = (filterType, value) => {
  if (filterType === 'reply') {
    // 如果点击的是已选中的按钮，则取消选择
    if (selectedFilters.value.reply === value) {
      selectedFilters.value.reply = null;
    } else {
      selectedFilters.value.reply = value;
    }
  } else if (filterType === 'waiting') {
    // 切换待回复状态
    selectedFilters.value.waiting = !selectedFilters.value.waiting;
  } else if (filterType === 'unread') {
    // 切换未读状态
    selectedFilters.value.unread = !selectedFilters.value.unread;
  }
  
  console.log('当前筛选条件:', selectedFilters.value);
};
</script>

<style scoped>
.left {
  background-color: #FFF;
  height: calc(100vh - 40px);
  width: 280px;
  margin-right: 12px;
  border-radius: 10px;
  display: flex;
  flex-direction: column;
}

.leftSearch {
  width: 100%;
  height: 54px;
  display: flex;
  align-items: center;
}

.leftDropdown {
  margin-left: 10px;
}

.leftTitle {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.leftTitleText {
  margin-right: 2px;
  font-size: 12px;
  color: #333;
  margin-left: 2px;
  margin-top: 12px;
  transition: color 0.3s;
  position: relative;
  cursor: pointer;
  padding-bottom: 4px;
}

.leftTitleText::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 1px;
  background: #ddd;
}

.activeText::before {
  content: '';
  position: absolute;
  bottom: 0;
  left: 0;
  width: 100%;
  height: 2px;
  background: #20c35c;
  z-index: 1;
}

.activeText {
  color: #20c35c !important;
}

.leftData {
  width: 100%;
  height: 41px;
  background-color: #f7f8fa;
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 10px;
}

.leftData span {
  color: #999;
  font-family: PingFang SC, PingFangSC, -apple-system, sans-serif !important;
}

.overLeft {
  overflow-y: auto;
}

.overLeft::-webkit-scrollbar {
  display: none;
}

.leftList {
  width: 100%;
}

.leftListBox {
  width: 98%;
  height: 120px;
  display: flex;
  margin-top: 20px;
  /* padding-left: 5px; */
}

.leftListBoxRight {
  width: 300px;
  margin-left: 12px;
  margin-top: 10px;
  color: #999;
  font-size: 14px;
}

.leftListBoxRightTop {
  display: flex;
  align-items: center;
  justify-content: space-between;
  font-size: 12px;
  line-height: 1.4;
  white-space: nowrap;
  font-weight: 500;
  color: black;
}

.leftListBoxRightCenter {
  color: #7a8a9d;
  display: flex;
  font-size: 12px;
  margin-top: 5px;
}

.leftListBoxRightBottom {
  display: flex;
  align-items: center;
  justify-content: space-between;
  margin-top: 12px;
  margin-left: -5px;
}

.leftListBox:hover {
  background-color: #f6fdf8;
}

.leftListBox:active {
  background-color: #e9ffef;
}

.message-content {
  display: flex;
  align-items: center;
  justify-content: space-between;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  width: 100%;
  min-height: 22px; /* 添加最小高度确保空内容时也保持一致的高度 */
}

.message-text {
  flex: 1;
  overflow: hidden;
  text-overflow: ellipsis;
  margin-right: 8px;
  min-width: 0; /* 确保文本可以正确缩小 */
}
.leftDataText {
  cursor: pointer;
}

.refreshing {
  animation: rotate 1s linear infinite;
}

@keyframes rotate {
  from {
    transform: rotate(0deg);
  }
  to {
    transform: rotate(360deg);
  }
}
.contact-name {
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  display: inline-block;
}

/* 筛选菜单样式 */
.filter-menu {
  background: white;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  padding: 12px;
  width: 280px;
}

.filter-section {
  margin-bottom: 16px;
}

.filter-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 10px;
  font-size: 14px;
}

.filter-buttons {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.filter-button {
  color: black;
  margin-right: 8px;
  margin-bottom: 8px;
  border-radius: 4px;
  height: 32px;
  padding: 0 12px;
  background-color: rgb(241,244,249);
  border-color: rgb(241,244,249);
}

.filter-button:hover {
  background-color: #e0e0e0;
  border-color: #e0e0e0;
  color: black;
}

/* 选中按钮的样式 */
.selected-button {
  background-color: #25d466 !important;
  border-color: #25d466 !important;
  color: white !important;
}

.selected-button:hover {
  background-color: #20c35c !important;
  border-color: #20c35c !important;
  color: white !important;
}
</style>